package repository

import (
	"gorm.io/gorm/clause"
	"niu-video/app/model"
	"niu-video/pkg/db"
)

var RelationRepository = newRelationRepository()

func newRelationRepository() *relationRepository {
	return &relationRepository{}
}

type relationRepository struct {
	baseRepository
}

// 是否关注
func (u *relationRepository) IsFollow(followingId int64, userId int64) (r model.Relation) {
	db.DB.Where("following_id = ?", followingId).Where("follower_id = ?", userId).First(&r)
	return
}

func (u *relationRepository) Create(relation *model.Relation) (err error) {
	err = db.DB.Create(relation).Error
	return err
}

func (u *relationRepository) Delete(followingId int64, userId int64) (err error) {
	return db.DB.Where("following_id = ?", followingId).Where("follower_id = ?", userId).Delete(&model.Relation{}).Error
}

// 获取用户关注视频分页
func (u *relationRepository) GetUserFollowByPage(page int, pageSize int,
	userId int64) (videos []model.Video, err error) {
	order := clause.OrderByColumn{
		Column: clause.Column{
			Name: "create_time",
		},
		Desc: true,
	}
	err = db.DB.Debug().Table("video").
		Where("user_id IN (?)",
			db.DB.Table("relation").
				Select("DISTINCT following_id").
				Where("follower_id = ?", userId)).
		Order(order).
		Offset((page-1)*pageSize).
		Limit(pageSize).
		Where("is_delete", false).
		Find(&videos).Error
	if err != nil {
		return nil, err
	}
	return videos, nil
}
